﻿using PageAdmin.Utils.ORM;
using PageAdmin.Utils.ORM.PropertyDescriptor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace PageAdmin.Utils.BLL
{
    /// <summary>
    ///附件相关的BLL
    /// </summary>
    public class AttachmentDataBLL
    {

        /// <summary>
        /// 反射添加附件列表映射属性。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dbSet"></param>
        /// <param name="tModel"></param>
        /// <param name="id"></param>
        public static void SetAttachmentListProperty<T>(DbSet<T> dbSet, T tModel, int id,bool isDetail=true) where T : class, new()
        {
            IEnumerable<ModelFieldMapped> modelFieldMappedList = dbSet.ModelFieldMappingList.Where(c => c.IsAttachmentMapped == true);
            if (modelFieldMappedList.Count() == 0)
            {
                return;
            }
            PropertyInfo proInfo;
            if (id <= 0)
            {
                return;
            }
            IEnumerable<dynamic> attachmentList;
            string tableName = dbSet.TableName;
            if (isDetail)
            {
                modelFieldMappedList = modelFieldMappedList.Where(c => c.AttachmentMappedDescriptor.DetailSyncLoad == true);
            }
            else
            {
                modelFieldMappedList = modelFieldMappedList.Where(c => c.AttachmentMappedDescriptor.ListSyncLoad == true);
            }
            foreach (var item in modelFieldMappedList)
            {
                if (item.AttachmentMappedDescriptor.FileListPropertyInfo==null)                
                {
                    continue;//附件列表未映射到集合属性时则跳出
                }
                proInfo = item.AttachmentMappedDescriptor.FileListPropertyInfo;
                if (proInfo != null)
                {
                    attachmentList = GetAttachmentList(tableName, item.AttachmentMappedDescriptor.AttachmentFieldName, id, item.AttachmentMappedDescriptor.AttachmentFileListField);
                    proInfo.SetValue(tModel, attachmentList, null);
                }
            }

        }

        /// <summary>
        /// 同步更新附件记录
        /// </summary>
        /// <returns></returns>
        public static TipsInfo UpdateAttachmentState<T>(DbSet<T> dbSet, T tModel, int detailId) where T : class, new()
        {
            Type modelType = dbSet.ModelType;
            IEnumerable<ModelFieldMapped> modelFieldMappedList = dbSet.ModelFieldMappingList.Where(c => c.IsAttachmentMapped == true);
            TipsInfo tipsInfo = new TipsInfo();
            if (modelFieldMappedList.Count() == 0)
            {
                return tipsInfo;
            }
            string tableName = dbSet.TableName;
            PropertyInfo proInfo;
            foreach (ModelFieldMapped modelFieldMapping in modelFieldMappedList)
            {
                string attachmentFieldName = modelFieldMapping.AttachmentMappedDescriptor.AttachmentFieldName;
                proInfo = modelFieldMapping.PropertyInfo;
                string fieldContent = (string)proInfo.GetValue(tModel, null);
                if (proInfo != null)
                {
                    tipsInfo = SendUpdateAttachmentStateRequest(tableName, attachmentFieldName, fieldContent, detailId);
                    if (tipsInfo.State == 0)
                    {
                        return tipsInfo;
                    }
                }
            }
            return tipsInfo;
        }


        /// <summary>
        /// 删除主时同步删除主站附件表数据，仅改变状态state改为-1
        /// </summary>
        /// <returns></returns>
        public static TipsInfo DeleteAttachment(string parentTable, int parentId)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            WebApiHelper webApiHelper = new WebApiHelper();
            dictionary.Add("method", "AttachmentData.Delete");
            dictionary.Add("parentTable", parentTable);
            dictionary.Add("parentId", parentId.ToString());
            string result = webApiHelper.Post(dictionary);
            var tipsInfo = JsonHelper.DeserializeObject<TipsInfo>(result);
            return tipsInfo;
        }


        /// <summary>
        /// 更新状态的请求
        /// </summary>
        /// <returns></returns>
        private static TipsInfo SendUpdateAttachmentStateRequest(string parentTable, string parentField, string fieldContent, int id)
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            WebApiHelper webApiHelper = new WebApiHelper();
            dictionary.Add("method", "AttachmentData.UpdateState");
            dictionary.Add("parentTable", parentTable);
            dictionary.Add("parentField", parentField);
            dictionary.Add("parentId", id.ToString());
            dictionary.Add("content", fieldContent);
            string result = webApiHelper.Post(dictionary);
            var tipsInfo = JsonHelper.DeserializeObject<TipsInfo>(result);
            return tipsInfo;
        }

        /// <summary>
        ///  获取附件列表
        /// </summary>
        /// <param name="parentTable"></param>
        /// <param name="parentField"></param>
        /// <param name="parentId"></param>
        /// <param name="fileListFields"></param>
        /// <returns></returns>
        private static IEnumerable<dynamic> GetAttachmentList(string parentTable, string parentField, int parentId, string fileListFields = "*")
        {
            WebApiHelper webApi = new WebApiHelper();
            Dictionary<string, string> directory = new Dictionary<string, string>();
            directory.Add("method", "AttachmentData.GetList");
            directory.Add("parentTable", parentTable);
            directory.Add("parentField", parentField);
            directory.Add("fileListFields", fileListFields);
            directory.Add("parentId",StringHelper.Format<string>(parentId));
            IEnumerable<dynamic> attachmentList = new List<dynamic>();
            string result = webApi.Get(directory);
            if (string.IsNullOrEmpty(result)) return attachmentList;
            try
            {
                attachmentList = JsonHelper.DeserializeObject<List<dynamic>>(result);
            }
            catch (Exception ex)
            {
                return attachmentList;
            }
            return attachmentList;
        }
    }
}